package com.ly.auth.token;

import cn.hutool.core.bean.BeanUtil;
import com.ly.auth.entity.AuthUser;
import com.ly.auth.filter.AuthorizationRequestFilter;
import com.ly.common.core.domain.SysUser;
import com.ly.common.core.model.LoginUser;
import com.ly.common.core.utils.ip.IpUtils;
import com.ly.common.core.utils.uuid.IdUtils;
import com.ly.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class CustomTokenEnhancer implements TokenEnhancer {

    @Autowired
    private RedisService redisService;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        AuthUser user = (AuthUser) authentication.getPrincipal();
        String token = IdUtils.fastUUID();
        Long userId = user.getUserId();
        String userName = user.getUsername();
        //设置登录用户信息
        LoginUser loginUser = new LoginUser();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr());
        SysUser sysUser = new AuthUser();
        BeanUtil.copyProperties(user, sysUser);
        loginUser.setSysUser(sysUser);
        //自定义token信息
        Map<String, Object> additionalInformation = new HashMap<>();
        additionalInformation.put("user_key", token);
        additionalInformation.put("user_id", userId);
        additionalInformation.put("username", userName);

        //ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        //HttpSession session = attr.getRequest().getSession(true); // true == allow create
        //String sessionId = session.getId();
        String sessionId = AuthorizationRequestFilter.threadSessionParam.get();
        log.info("==============>生产token的session={}", sessionId);
        additionalInformation.put("sessionId", sessionId);

        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
        //将token存入redis
        this.refreshToken(loginUser);
        return accessToken;
    }

    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + 43200000L);
        String userKey = this.getTokenKey(loginUser.getToken());
        this.redisService.setCacheObject(userKey, loginUser, 720L, TimeUnit.MINUTES);
    }

    private String getTokenKey(String token) {
        return "login_tokens:" + token;
    }

}
